const Service = require('egg').Service;
const RandExp = require('randexp');
const source = require("../../public/source.js");
const random = require("./random.js");
const array = require("./array.js");
const time = require('./time.js');
const tables = require("../../public/tables.js");
const opts = require("../../public/opts.js");
const brands = require("../../public/brands.js");
// const dicts = require("../../public/dicts.js");
const address = require("../../public/address.js");


class FieldsService extends Service {
    async query(sql) {
        return await this.app.mysql.query(sql);
    }
    tableTotal(tabName) {
        return tables.filter(item => item.name == tabName)[0].total;
    }
    adsIds(proInd, citInd) {  //地址前缀inds   [proInd, citInd, couInd]
        proInd = proInd !== undefined ? proInd : random.numByMax(address.length);
        citInd = citInd !== undefined ? citInd : random.numByMax(address[proInd].city.length);
        let couInd = random.numByMax(address[proInd].city[citInd].county.length);
        return [proInd, citInd, couInd];
    }
    adsDetail() {    //地址后缀名
        let streetLen = random.eleOfArr([2, 3, 4]);
        let roadLen = random.eleOfArr([2, 3, 4]);
        let words = source.address.words;
        let streetName = "", roadName = "";
        for (let i = 0; i < streetLen; i++) {
            streetName += random.eleOfArr(words);
        }
        for (let i = 0; i < roadLen; i++) {
            roadName += random.eleOfArr(words);
        }
        let num = random.numByWeight([[80, "(0,500]"], [15, "(500,800]"], [4, "(800,900]"], [1, "(900,1000)"]]);
        return `'${streetName}街道${roadName}路${num}号'`;
    }
    tel() {
        return `'${new RandExp(source.regexp.tel).gen()}'`;
    }
    psd() {
        return `'${new RandExp(source.regexp.psd).gen()}'`;
    }
    name() {
        let name = random.strJoinFromArrs(...source.nameWords);
        Math.random() < 0.5 && (name += random.strJoinFromArrs(source.nameWords[1]));
        return `'${name}'`;
    }
    sex() {
        return random.numByWeight(source.sexWeight);
    }
    nickname() {
        let nickname = "";
        let length = random.eleOfArr(array.byArea("[1,10]"))
        for (let i = 0; i < length; i++) {
            nickname += random.strJoinFromArrs(source.nameWords.flat());
        }
        return `'${nickname}'`;
    }
    identity() {
        return `'${new RandExp(source.regexp.identity).gen()}'`;
    }
    avatar() {
        return `'${random.strJoinFromArrs(source.avatars)}'`;
    }
    admin = {
        tel: this.tel,
        psd: this.psd,
        name: this.name,
        sex: this.sex,
        nickname: this.nickname,
        type: (i, total) => {    ////0超级管理员1普通管理员
            return i == 0 ? 0 : 1;
        },
        identity: this.identity,
    }
    user = {
        _inTime: "",
        _outTime: "now",
        tel: this.tel,
        psd: this.psd,
        avatar: this.avatar,
        nickname: this.nickname,
        name: this.name,
        sex: this.sex,
        birthday: (i, total) => {
            return `'${random.timeByArea("-50Y").split(" ")[0]}'`;
        },
        inTime: (i, total) => {
            this.user._inTime = random.timeByArea("-180D", "-1D");
            return `'${this.user._inTime}'`;
        },
        outTime: (i, total) => {
            let time = Math.random() < 0.02 ? random.timeByArea(this.user._inTime) : null;
            this.user._outTime = time;
            return time ? `'${time}'` : `null`;
        },
        lastTime: (i, total) => {
            let endTime = this.user._outTime ? this.user._outTime : "now";
            let lastTime = random.timeByArea(this.user._inTime, endTime);
            return `'${lastTime}'`;
        },
        coin: (i, total) => {
            return random.numByArea("[0,10000]")
        },
        status: (i, total) => {    //状态:0禁用1正常2注销
            return random.numByWeight([[5, [0]], [90, [1]], [5, [2]]]);
        },
    }
    courier = {
        _citInd: 0,
        _couInd: 0,
        provinceId: (i, total) => {
            let [proInd, citInd, couInd] = this.adsIds();
            this.courier._citInd = citInd;
            this.courier._couInd = couInd;
            return proInd;
        },
        cityId: (i, total) => {
            return this.courier._citInd;
        },
        countyId: (i, total) => {
            return this.courier._couInd;
        },
        detailAddress: (i, total) => {
            return `${this.adsDetail()}`;
        },
        tel: (i, total) => {
            return `${this.tel()}`;
        },
        name: (i, total) => {
            return `${this.name()}`;
        }
    }
    voucher = {
        _id: 0,
        _useCase: 0,
        _startTime: "",
        _endTime: "",
        useCase: (i, total) => {
            this.voucher._id = i + 1;
            this.voucher._useCase = random.numByWeight([[20, [0]], [40, [1, 2, 3, 4]], [40, [11, 12, 13, 14, 15]]]);
            return this.voucher._useCase;
        },
        faceVal: (i, total) => {
            let arr = [];
            switch (this.voucher._useCase) {
                case 0: arr = [[100, [100]]]; break;
                case 1:
                case 2:
                case 3:
                case 4: arr = [[100, [10, 20, 30, 40, 50]]]; break;
                case 11:
                case 12:
                case 13:
                case 14:
                case 15: arr = [[100, [60, 70, 80, 90, 100]]]; break;
                default: break;
            }
            return random.numByWeight(arr)
        },
        startTime: (i, total) => {
            this.voucher._startTime = random.timeByArea(time.format("-20D")).split(" ")[0] + " 00:00:00";
            return `'${this.voucher._startTime}'`;
        },
        endTime: (i, total) => {
            let endTime = time.byTimeLong(this.voucher._startTime, "+15D").split(" ")[0] + " 23:59:59";
            this.voucher._endTime = endTime;
            return `'${endTime}'`
        },
        amount: (i, total) => {
            return random.numByMax(10000);
        },
        theme: (i, total) => {
            let type = 0;     //0新人优惠券1节日优惠券2年限优惠券3满减优惠券
            if (this.voucher._useCase == 0) {
                type = random.eleOfArr([0, 1]);
            } else {
                type = random.eleOfArr([1, 2, 3])
            }
            return type;
        },
        foreigns: {
            voucherLog: {
                _userId: 0,
                _userTotal: 0,
                userId: (i, total) => {
                    if (!this.voucher.foreigns.voucherLog._userTotal) {
                        this.voucher.foreigns.voucherLog._userTotal = this.tableTotal("user");
                    }
                    let userId = random.numByMax(this.voucher.foreigns.voucherLog._userTotal, "ceil");
                    this.voucher.foreigns.voucherLog._userId = userId;
                    return userId;
                },
                voucherId: (i, total) => {
                    return this.voucher._id;
                },
                getTime: async (i, total) => {
                    let end = await this.app.mysql.select("user", {
                        where: { id: this.voucher.foreigns.voucherLog._userId },
                        columns: ["inTime"]
                    })
                    let inTime = end[0].inTime;
                    let { _startTime, _endTime } = this.voucher;
                    let sTime = this.service.utility.getValest([inTime, _startTime], "max");
                    let eTime = this.service.utility.getValest([_endTime, time.format("now")]);
                    let getTtime = random.timeByArea(sTime, eTime);
                    return `'${getTtime}'`;
                }
            }
        }
    }
    subbranch = {
        _citInd: 0,
        _couInd: 0,
        provinceId: (i, total) => {
            let ind = i % this.app.provinceTotal;
            let [proInd, citInd, couInd] = this.adsIds(ind);
            this.courier._citInd = citInd;
            this.courier._couInd = couInd;
            return proInd;
        },
        cityId: (i, total) => {
            return this.courier._citInd;
        },
        countyId: (i, total) => {
            return this.courier._couInd;
        },
        detailAddress: (i, total) => {
            return `${this.adsDetail()}`;
        },
        managerTel: (i, total) => {
            return `${this.tel()}`;
        },
        managerName: (i, total) => {
            return `${this.name()}`;
        }
    }
    goods = {
        _marketTime: "",
        _cameraFront: 0,
        _yearInd: 0,
        _baseNames: {
            max: 0,
            spreadNames: [],  //手机的传播名,数组元素会减少
            allIndexs: [],   //所有的indexs的元素集合[[0,0,0,0],[0,0,0,1]……]，数组元素会减少
            fillIndexs: []    //all单个元素数组的各个元素的最大下标值,例如：[4,3,4.5]
        },
        _currInds: [],   //当前的商品的品牌、系列、代数、型号的下标 [0,0,0,0]
        // _currInd: 0,   //随机产生的_currInds 的ind
        _baseName: "",
        _index: 0,
        _brandImgsFirst: "",
        _baseBattery: 0,
        _baseCpuCores: "",
        _cameraBehind: 0,
        _showResolution: 0,
        _showSize: 0,
        _flat: {
            cameraPixel: [],
            battery: [],
            cpuCores: [],
            resolution: [],
            ram: [],
            rom: [],
        },
        marketTime: (i, total) => {
            this.goods._index = i + 1;
            let marketTime = random.timeByArea("-4Y", "now").split(" ")[0];
            let yearInd = 4 - Math.round(parseInt(time.diff(marketTime, "now", "Y")));
            this.goods._marketTime = marketTime;
            this.goods._yearInd = yearInd;
            if (this.goods._flat.cameraPixel.length == 0) {
                this.goods._flat.cameraPixel = source.goods.cameraPixel.flat(1);
                this.goods._flat.battery = source.goods.battery.flat(1);
                this.goods._flat.cpuCores = Array.from(new Set(source.goods.cpuCores.flat(1)));
                this.goods._flat.resolution = source.goods.resolution.flat(1);
                this.goods._flat.ram = Array.from(new Set(source.goods.ram.flat(1)));
                this.goods._flat.rom = Array.from(new Set(source.goods.rom.flat(1)));
            }
            return `'${marketTime}'`;
        },
        cameraFront: (i, total) => {
            this.goods._cameraFront = random.eleOfArr(source.goods.cameraPixel[this.goods._yearInd]);
            return this.goods._cameraFront;
        },
        cameraBehind: (i, total) => {
            let cameraBehind = random.eleOfArr(source.goods.cameraPixel[this.goods._yearInd]);
            this.goods._cameraBehind = cameraBehind;
            return cameraBehind;
        },
        showResolution: (i, total) => {
            let resolution = random.eleOfArr(source.goods.resolution[this.goods._yearInd]);
            this.goods._showResolution = resolution;
            return `'${resolution}'`;
        },
        showSize: (i, total) => {
            let size = random.eleOfArr(source.goods.showSize);
            this.goods._showSize = size;
            return size;
        },
        networkType: (i, total) => {
            return 1;   //1 SA/NSA双模(5G)
        },
        networkMode: (i, total) => {
            return 1;    //1双卡双待
        },
        baseName: (i, total) => {
            let brands = source.goods.brands;
            let baseNames = this.goods._baseNames;
            if (baseNames.max == 0) {
                for (let i = 0; i < brands.length; i++) {
                    let series = brands[i].series;
                    for (let j = 1; j < series.length; j++) {
                        let gene = series[j].generation;
                        let type = series[j].generationType;
                        if (gene) {
                            for (let m = 0; m < gene.length; m++) {
                                for (let n = 0; n < type.length; n++) {
                                    let spreadName = brands[i].name + " " + series[j].name + " " + gene[m] + " " + type[n];
                                    baseNames.max++;
                                    baseNames.spreadNames.push(spreadName);
                                    baseNames.allIndexs.push([i, j, m, n]);
                                    if (baseNames.fillIndexs.length == 0) {
                                        baseNames.fillIndexs = [brands.length - 1, series.length - 1, gene.length - 1, type.length - 1];
                                    }
                                }
                            }
                        }
                    }
                }
            }
            let ind = random.numByMax(baseNames.allIndexs.length);
            let baseName = baseNames.spreadNames.splice(ind, 1)[0];
            this.goods._currInds = baseNames.allIndexs.splice(ind, 1)[0];
            // this.goods._currInd = ind;
            this.goods._baseName = baseName;
            return `'${baseName}'`;
        },
        baseBrand: (i, total) => {
            let inds = this.goods._currInds;
            let brand = source.goods.brands[inds[0]].id;
            return brand;
        },
        baseSeries: (i, total) => {
            let inds = this.goods._currInds;
            let series = source.goods.brands[inds[0]].series[inds[1]].id;
            return series;
        },
        baseBattery: (i, total) => {
            let baseBattery = random.eleOfArr(source.goods.battery[this.goods._yearInd]);
            this.goods._baseBattery = baseBattery;
            return baseBattery;
        },
        baseCpuCores: (i, total) => {
            let cpuCores = random.eleOfArr(source.goods.cpuCores[this.goods._yearInd]);
            this.goods._baseCpuCores = cpuCores;
            return `'${cpuCores}'`;
        },
        baseCpuBrand: (i, total) => {
            let cpuBrand = "";
            let brandName = source.goods.brands[this.goods._currInds[0]].name;
            switch (brandName) {
                case "HuaWei":
                case "Honor":
                    cpuBrand = "海思"; break;
                case "XiaoMi":
                case "RedMi":
                    cpuBrand = "高通"; break;
                case "Oppo":
                    cpuBrand = "联发科"; break;
                case "Vivo":
                    cpuBrand = "高通"; break;
                default:
                    cpuBrand = "未知"; break;
            }
            return `'${cpuBrand}'`;
        },
        imgs: (i, total) => {
            let brandName = source.goods.brands[this.goods._currInds[0]].name;
            let ele = random.eleOfArr(source.goods[brandName]);
            this.goods._brandImgsFirst = ele[0];
            let imgs = array.order(ele, "no");
            return `'${imgs.toString().replace(/,/g, ";")}'`;
        },
        title: (i, total) => {
            let { _baseName } = this.goods;
            let title = "【" + _baseName + "】";
            let sourceTitle = source.goods.title;
            let len = random.numByMax(sourceTitle.length, "ceil");
            for (let i = 0; i < len; i++) {
                let text = random.eleOfArr(sourceTitle);
                !title.includes(text) && (title += text);
            }
            return `'${title}'`;
        },
        status: (i, total) => {
            return random.numByWeight([[2, [0]], [98, [1]]]);    //商品状态：0下架（注销）1上架
        },
        foreigns: {
            goodsStyle: {
                _ram: 0,
                _rom: 0,
                _groups: [],
                _currGroup: [],
                _colors: [],
                goodsId: (i, total) => {
                    let { _groups, _colors } = this.goods.foreigns.goodsStyle;
                    if (_groups.length == 0) {
                        let { _yearInd } = this.goods;
                        let rams = source.goods.ram[_yearInd];
                        let roms = source.goods.rom[_yearInd];
                        _colors = array.clone(source.goods.colors);
                        let subColors = random.arrOfArr(_colors, [3, 4, 5]);
                        rams.forEach(ram => {
                            roms.forEach(rom => {
                                subColors.forEach(color => {
                                    _groups.push(`${ram};${rom};${color}`);
                                })
                            })
                        })
                    }
                    this.goods.foreigns.goodsStyle._currGroup = _groups.splice(random.numByMax(_groups.length), 1)[0].split(";");
                    return this.goods._index;
                },
                ram: (i, total) => {
                    let ram = parseInt(this.goods.foreigns.goodsStyle._currGroup[0]);
                    this.goods.foreigns.goodsStyle._ram = ram;
                    return ram;
                },
                rom: (i, total) => {
                    let rom = parseInt(this.goods.foreigns.goodsStyle._currGroup[1]);
                    this.goods.foreigns.goodsStyle._rom = rom;
                    return rom;
                },
                color: (i, total) => {
                    return `'${this.goods.foreigns.goodsStyle._currGroup[2]}'`;
                },
                colorImg: (i, total) => {
                    return `'${this.goods._brandImgsFirst}'`;
                },
                price: (i, total) => {
                    let price = 0;
                    let { showSize } = source.goods;
                    let { battery, cpuCores, cameraPixel, resolution, ram, rom } = this.goods._flat;
                    let { _baseBattery, _baseCpuCores, _cameraFront, _cameraBehind, _showResolution, _showSize, _marketTime } = this.goods;
                    let { _ram, _rom } = this.goods.foreigns.goodsStyle;
                    let batteryWeight = 5, cpuCoresWeight = 100, cameraFrontWeight = 5, cameraBehindWeight = 5, showResolutionWeight = 5, showSizeWeight = 5, ramWeight = 300, romWeight = 150, newWeight = 1000;
                    price += battery.indexOf(_baseBattery) * batteryWeight;
                    price += cpuCores.indexOf(_baseCpuCores) * cpuCoresWeight;
                    price += cameraPixel.indexOf(_cameraFront) * cameraFrontWeight;
                    price += cameraPixel.indexOf(_cameraBehind) * cameraBehindWeight;
                    price += resolution.indexOf(_showResolution) * showResolutionWeight;
                    price += showSize.indexOf(_showSize) * showSizeWeight;
                    price += ram.indexOf(_ram) * ramWeight;
                    price += rom.indexOf(_rom) * romWeight;
                    // console.log(battery.indexOf(_baseBattery) * batteryWeight, cpuCores.indexOf(_baseCpuCores) * cpuCoresWeight, cameraPixel.indexOf(_cameraFront) * cameraFrontWeight, cameraPixel.indexOf(_cameraBehind) * cameraBehindWeight, resolution.indexOf(_showResolution) * showResolutionWeight, showSize.indexOf(_showSize) * showSizeWeight, ram.indexOf(_ram) * ramWeight
                    //     , rom.indexOf(_rom) * romWeight)
                    new Date(_marketTime).getFullYear() == new Date().getFullYear() && (price += newWeight);
                    return price;
                },
                inventory: (i, total) => {
                    return random.numByMax(1000);
                }
            }
        }
    }
    station = {
        _level: 0,   //0普通快递 1物流分拣中心
        _citInd: 0,
        _couInd: 0,
        _currProInd: 0,
        _currCitInd: 0,
        _currCouInd: 0,
        _countLevel: 0,
        provinceId: (i, total) => {
            let { _currProInd, _currCitInd, _currCouInd } = this.station;
            let [proInd, citInd, couInd] = [_currProInd, _currCitInd, _currCouInd];
            this.station._citInd = citInd;
            this.station._couInd = couInd;
            this.station._currCouInd++;
            if (this.station._currCouInd == address[_currProInd].city[_currCitInd].county.length) {
                this.station._currCitInd++;
                this.station._currCouInd = 0;
                if (this.station._currCitInd == address[_currProInd].city.length) {
                    this.station._currProInd++;
                    this.station._currCitInd = 0;
                    if (this.station._currProInd == address.length) {
                        this.station._currProInd = 0;
                    }
                }
            }
            if (this.station._currCouInd == 0 && this.station._countLevel <= this.app.cityTotal) {
                this.station._level = 1;
                this.station._countLevel++;
            } else {
                this.station._level = 0;
            }
            // this.station._level = 2;






            // if (i < stationTotals[0]) {
            //     let { _currProInd } = this.station;
            //     [proInd, citInd, couInd] = this.adsIds(_currProInd);
            //     this.station._currProInd++;
            //     if (this.station._currProInd == address.length) {
            //         this.station._currProInd = 0;
            //     }
            // } else if (i < stationTotals[1]) {
            //     let { _currProInd, _currCitInd } = this.station;
            //     [proInd, citInd, couInd] = this.adsIds(_currProInd, _currCitInd);
            //     this.station._level = 1;
            //     this.station._currCitInd++;
            //     if (this.station._currCitInd == address[_currProInd].city.length) {
            //         this.station._currProInd++;
            //         this.station._currCitInd = 0;
            //         if (this.station._currProInd == address.length) {
            //             this.station._currProInd = 0;
            //         }
            //     }
            // } else {
            //     let { _currProInd, _currCitInd, _currCouInd } = this.station;
            //     [proInd, citInd, couInd] = [_currProInd, _currCitInd, _currCouInd];
            //     this.station._level = 2;
            //     this.station._currCouInd++;
            //     if (this.station._currCouInd = address[_currProInd].city[_currCitInd].county.length) {
            //         this.station._currCitInd++;
            //         this.station._currCouInd = 0;
            //         if (this.station._currCitInd == address[_currProInd].city.length) {
            //             this.station._currProInd++;
            //             this.station._currCitInd = 0;
            //             if (this.station._currProInd == address.length) {
            //                 this.station._currProInd = 0;
            //             }
            //         }
            //     }
            // }
            // this.station._couInd = couInd;
            // this.station._citInd = citInd;
            return proInd;
        },
        cityId: (i, total) => {
            return this.station._citInd;
        },
        countyId: (i, total) => {
            return this.station._couInd;
        },
        suffixName: (i, total) => {
            let name = random.eleOfArr(source.address.stationType[this.station._level]);
            return `'${name}'`;
        },
        detailAddress: (i, total) => {
            return `${this.adsDetail()}`;
        },
        level: (i, total) => {
            return this.station._level;
        }
    }
    getGoodsInfo = {
        _userId: 0,
        _userTel: "",
        _userName: "",
        _inTime: "",
        _currCitys: [],
        _currCountys: [],
        _citInd: 0,
        _couInd: 0,
        userId: async () => {
            let userTotal = this.tableTotal("user");
            let userId = random.numByMax(userTotal, "ceil");
            this.getGoodsInfo._userId = userId;
            let end = await this.app.mysql.select("user", {
                where: { id: userId },
                columns: ["name", "tel", "inTime"]
            })
            this.getGoodsInfo._userTel = end[0].tel;
            this.getGoodsInfo._userName = end[0].name;
            this.getGoodsInfo._inTime = end[0].inTime;
            return userId;
        },
        userName: () => {
            return `'${this.getGoodsInfo._userName}'`;
        },
        userTel: () => {
            return `'${this.getGoodsInfo._userTel}'`;
        },
        provinceId: () => {
            let [proInd, citInd, couInd] = this.adsIds();
            this.getGoodsInfo._citInd = citInd;
            this.getGoodsInfo._couInd = couInd;
            return proInd;
        },
        cityId: () => {
            return this.getGoodsInfo._citInd;
        },
        countyId: () => {
            return this.getGoodsInfo._couInd;
        },
        detail: () => {
            return `${this.adsDetail()}`;
        },
        editTime: () => {
            let time = random.timeByArea(this.getGoodsInfo._inTime, "now");
            return `'${time}'`;
        },
    }
    deal = {
        _id: 0,
        _status: 0,
        _userId: 0,
        _userInTime: "",
        _startTime: "",
        _getGoodsInfoId: 0,
        _voucherAllIds: [],
        userId: async (i, total) => {
            let sql = `select DISTINCT userId from get_goods_info ORDER BY rand() limit 1;`;
            let end = await this.query(sql);
            let userId = end[0].userId;
            this.deal._userId = userId;
            this.deal._id = i + 1;
            return userId;
        },
        status: (i, total) => { //交易状态： 0待付款；1待发货；2待收货；3待评价；4已完成交易；5已关闭交易
            let status = random.numByWeight([[8, [0]], [90, "[1,4]"], [2, [5]]])
            this.deal._status = status;
            return status;
        },
        startTime: async (i, total) => {
            let end = await this.app.mysql.select('user', {
                where: { id: this.deal._userId },
                columns: ['inTime']
            });
            let inTime = time.format(end[0].inTime);
            this.deal._userInTime = inTime;
            let area = "";
            switch (this.deal._status) {
                case 0: area = "-24h"; break;
                case 1: area = `-${random.numByWeight([[80, `[0,${24 * 60})`], [20, `[${24 * 60},${48 * 60}]`]])}m`; break;
                case 2: area = `-${random.numByWeight([[20, `[${24 * 60},${60 * 60})`], [60, `[${60 * 60},${96 * 60})`], [20, `[${96 * 60},${144 * 60})`]])}m`; break;
                case 3: area = `-${random.numByWeight([[20, `[${2 * 24 * 60},${4 * 24 * 60})`], [80, `[${4 * 24 * 60},${15 * 24 * 60})`]])}m`; break;
                case 4: area = `-${random.numByWeight([[80, `[0,${30 * 24})`], [20, `[${30 * 24},${90 * 24})`]])}h`; break;
                case 5: area = inTime; break;
                default: break;
            }
            let startTime = random.timeByArea(area);
            startTime = this.service.utility.getValest([startTime, inTime], "max");
            this.deal._startTime = startTime;
            return `'${startTime}'`;
        },
        endTime: (i, total) => {
            let endTime = null;
            let startTime = this.deal._startTime;
            if (this.deal._status == 4) {
                let hours = random.numByWeight([[10, `[${24 * 3},${24 * 5})`], [40, `[${24 * 5},${24 * 15})`], [50, [24 * 15]]]);
                endTime = random.timeByArea(startTime, time.byTimeLong(startTime, `+${hours}h`));
            } else if (this.deal._status == 5) {
                let minutes = random.numByWeight([[40, `[0,${60})`], [10, `[60,${24 * 60})`], [50, [24 * 60]]]);
                endTime = random.timeByArea(startTime, time.byTimeLong(startTime, `+${minutes}m`));
            }
            return !endTime ? 'null' : `'${endTime}'`;
        },
        voucherLogIds: async (i, total) => {
            let sql = `select id from voucher_log where userId=${this.deal._userId} order by rand() limit ${random.numByMax(3, "ceil")}`;
            let end = await this.query(sql);
            let ids = [];
            end.forEach(item => {
                ids.push(item.id);
            })
            return `'${ids.toString().replace(/,/g, ";")}'`;
        },
        note: (i, total) => {
            return `'${'随便写的备注信息'}'`;
        },
        getGoodsInfoId: async (i, total) => {
            let sql = `select id from get_goods_info where userId=${this.deal._userId} order by rand() LIMIT 1`;
            let end = await this.query(sql);
            this.deal._getGoodsInfoId = end[0].id;
            return end[0].id;
        },
        foreigns: {
            dealList: {
                _ram: 0,
                _rom: 0,
                _color: "",
                _goodsId: 0,
                dealId: async (i, total) => {
                    let goodsId = random.numByMax(this.tableTotal("goods"), "ceil");
                    let sql = `select color,ram,rom from goods_style where goodsId=${goodsId} order by rand() limit 1;`;
                    let end = await this.query(sql);
                    let { color, ram, rom } = end[0];
                    this.deal.foreigns.dealList._ram = ram;
                    this.deal.foreigns.dealList._rom = rom;
                    this.deal.foreigns.dealList._color = color;
                    this.deal.foreigns.dealList._goodsId = goodsId;
                    return this.deal._id;
                },
                goodsId: (i, total) => {
                    return this.deal.foreigns.dealList._goodsId;
                },
                color: async (i, total) => {
                    return `'${this.deal.foreigns.dealList._color}'`;
                },
                ram: async (i, total) => {
                    return `${this.deal.foreigns.dealList._ram}`;
                },
                rom: async (i, total) => {
                    return `${this.deal.foreigns.dealList._rom}`;
                },
                setMeal: (i, total) => {
                    return random.numByMax(opts.setMeals.length);
                },
                amount: (i, total) => {
                    return random.numByWeight([[90, [1]], [8, [2]], [2, [3]]]);
                },
                unitPrice: async (i, total) => {
                    let { _goodsId, _ram, _rom } = this.deal.foreigns.dealList;
                    let end = await this.app.mysql.select("goods_style", {
                        where: { goodsId: _goodsId, ram: _ram, rom: _rom },
                        columns: ["price"]
                    });
                    return end[0].price;
                }
            },
            transfer: {
                _dealId: null,
                _stationId: null,
                _arriveTime: null,
                _stationTotal: 0,
                _startTime: "",
                dealId: async (i, total) => {
                    //交易状态： 0待付款；1待发货；2待收货；3待评价；4已完成交易；5已关闭交易
                    if (!this.deal.foreigns.transfer._stationTotal) {
                        this.deal.foreigns.transfer._stationTotal = this.tableTotal("station");
                    }
                    let status = this.deal._status;
                    let init = async (currTotal, status) => {
                        if (i < currTotal) {
                            let diffM = 0, minM = 5 * 60, maxM = 10 * 60;
                            let sTime = this.deal.foreigns.transfer._startTime;
                            if (!sTime) {
                                sTime = this.deal._startTime;
                                this.deal.foreigns.transfer._startTime = sTime;
                            }
                            diffM = time.diff(sTime, "now", "m");
                            if (diffM < maxM * currTotal) {
                                let diff = maxM - minM;
                                maxM = Math.floor(diffM / currTotal);
                                minM = maxM - diff;
                                minM < 0 && (minM = 0);
                            }
                            let eTime = time.byTimeLong(sTime, `+${random.numByArea(`[${minM * 3600},${maxM * 3600}]`)}s`);
                            this.deal.foreigns.transfer._dealId = this.deal._id;
                            this.deal.foreigns.transfer._arriveTime = random.timeByArea(sTime, eTime);
                            this.deal.foreigns.transfer._startTime = this.deal.foreigns.transfer._arriveTime;
                            if (status != 2 && i == currTotal - 1) {
                                let adsSql = `select provinceId,cityId,countyId from get_goods_info where id=${this.deal._getGoodsInfoId}`;
                                let adsEnd = await this.query(adsSql);
                                let { provinceId, cityId, countyId } = adsEnd[0];
                                let staSql = `select id from station where provinceId=${provinceId} and cityId=${cityId} and countyId=${countyId} order by rand() LIMIT 1`;
                                let staEnd = await this.query(staSql);
                                this.deal.foreigns.transfer._stationId = staEnd[0].id;
                            } else {
                                this.deal.foreigns.transfer._stationId = random.numByMax(this.deal.foreigns.transfer._stationTotal, "ceil");
                            }
                        }
                    }
                    switch (status) {
                        case 2: await init(5, status); break;
                        case 3: await init(total, status); break;
                        case 4: await init(total, status); break;
                        default: break;
                    }
                    return this.deal.foreigns.transfer._dealId;
                },
                stationId: (i, total) => {
                    return this.deal.foreigns.transfer._stationId;

                },
                arriveTime: (i, total) => {
                    return `'${this.deal.foreigns.transfer._arriveTime}'`;
                },
            }
        }
    }
    comment = {
        _type: 0,
        _stars: 0,
        _dealedIds: [],
        _dealListId: 0,
        dealListId: async (i, total) => {
            if (this.comment._dealedIds.length == 0) {
                let sql = `select dl.id from deal d INNER JOIN deal_list dl on d.id=dl.dealId WHERE d.status=4`;
                let end = await this.query(sql);
                end.forEach(item => {
                    this.comment._dealedIds.push(item.id);
                })
            }
            this.comment._dealListId = random.eleOfArr(this.comment._dealedIds);
            return this.comment._dealListId;
        },
        type: (i, total) => {   //0系统自动默认好评1用户手动评价
            let type = random.numByWeight([[30, [0]], [70, [1]]]);
            this.comment._type = type;
            return type;
        },
        stars: (i, total) => {  //星级评价：0非常差1很差2差3一般4很好5非常好
            let stars = 5;
            if (this.comment._type == 1) {
                stars = random.numByWeight([[50, [0, 1, 2, 3, 4]], [50, [5]]]);
            }
            this.comment._stars = stars;
            return stars;
        },
        content: (i, total) => {
            let cont = "";
            if (this.comment._type == 0) {
                cont = "系统自动默认好评!";
            } else {
                let key = this.comment._stars >= 4 ? "good" : "bad";
                cont = random.eleOfArr(source.comment[key]);
            }
            return `'${cont}'`;
        },
        imgs: async (i, total) => {
            let sql = `select g.baseBrand as brandCode from deal d INNER JOIN deal_list dl on d.id=dl.dealId INNER JOIN goods g on dl.goodsId=g.id WHERE dl.id=${this.comment._dealListId};`;
            let end = await this.query(sql);
            let brand = brands.filter(item => item.id = end[0].brandCode)[0].name;
            let ind = random.numByMax(2);
            let imgs = random.arrOfArr(source.goods[brand][ind], "30,0;40,2-3;20,4;10,5");
            return `'${imgs.toString().replace(/,/g, ";")}'`;
        },
        time: async (i, total) => {
            let sql = `select d.startTime as sTime from deal d INNER JOIN deal_list dl on d.id=dl.dealId WHERE dl.id=${this.comment._dealListId};`;
            let end = await this.query(sql);
            let sTime = end[0].sTime;
            let eTime = this.service.utility.getValest([time.byTimeLong(sTime, "+15D"), time.now()])
            return `'${random.timeByArea(sTime, eTime)}'`;
        },
        readAmount: (i, total) => {
            return random.numByMax(1000)
        }
    }
    shopCart = {
        goodsStyleId: async (i, total) => {
            let goodsId = random.numByMax(this.tableTotal("goods"), "ceil");
            let sql = `SELECT id from goods_style WHERE goodsId=${goodsId} ORDER BY RAND() LIMIT 1;`;
            let end = await this.query(sql);
            return end[0].id;
        },
        userId: (i, total) => {
            return random.numByMax(this.tableTotal("user"), "ceil");
        },
        amount: (i, total) => {
            return random.numByWeight([[60, [1]], [30, [2, 3]], [10, [4, 5]]]);
        },
        setMeal: (i, total) => {
            return random.numByMax(opts.setMeals.length);
        },
        time: (i, total) => {
            return random.timeByArea("-15D");
        }
    }
    manageLog = {
        _operateObj: 0,
        _operaterId: 0,
        operateObj: (i, total) => {   //操作对象：0普通管理员1用户2商品基本参数(goods表)3商品款式(goods_style表)
            let code = random.numByMax(4);
            this.manageLog._operateObj = code;
            return code;
        },
        operaterId: (i, total) => {  //主动操作者
            let id = this.manageLog.operateObj == 0 ? 1 : random.numByMax(this.tableTotal("admin"));
            this.manageLog._operaterId = id;
            return id;
        },
        operateType: (i, total) => {   //操作类型：0新增1注销2修改3永久删除
            return random.numByMax(4);
        },
        operatedId: async (i, total) => {   //被操作者(管理员、商品、用户等)id
            let id = 0;
            let getCase3Id = async () => {
                let sql = `select count(*) as total from goods_style;`;
                let end = await this.query(sql);
                let id = random.numByMax(end[0].total, "ceil");
                return id;
            }
            switch (this.manageLog._operateObj) {
                case 0: id = random.numByMax(this.tableTotal("admin"), "ceil"); break;
                case 1: id = random.numByMax(this.tableTotal("user"), "ceil"); break;
                case 2: id = random.numByMax(this.tableTotal("goods"), "ceil"); break;
                case 3: id = await getCase3Id(); break;
                default: break;
            }
            return id;
        },
        time: (i, total) => {
            return `'${random.timeByArea("-90D")}'`;
        }
    }
}
module.exports = FieldsService;